import { Component, OnInit } from '@angular/core';
import {StockService, Stock } from '../stock.service';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';


@Component({
  selector: 'app-stockform',
  templateUrl: './stockform.component.html',
  styleUrls: ['./stockform.component.css']
})
export class StockformComponent implements OnInit {
 
  fromModel:FormGroup;

  stock:Stock;
  private cateqories:Array<string> = ["IT","互联网","金融"];
 

  constructor(private routerInfo: ActivatedRoute, private stockService: StockService,
    private router: Router) { }

  ngOnInit() {
    
    let stockId = this.routerInfo.snapshot.params["id"];
    this.stock = this.stockService.getStock(stockId);
    
    let fb = new FormBuilder();
    this.fromModel = fb.group({
      name:[this.stock.name,[Validators.required,Validators.minLength(3)]],
      price:[this.stock.price,[Validators.required]],
      desc:[this.stock.desc],
      cateqories:fb.array([
        new FormControl(this.stock.cateqories.indexOf(this.stock.cateqories[0]) != -1),
        new FormControl(this.stock.cateqories.indexOf(this.stock.cateqories[1]) != -1),
        new FormControl(this.stock.cateqories.indexOf(this.stock.cateqories[2]) != -1)
      ])
    });

    
  }

  cuncel(){
    this.router.navigateByUrl('/stock')
  }
  save(){
    var chineseCategories =[];
    var index = 0;
    for (let i = 0; i < 3; i++) {
      if(this.fromModel.value.cateqories[i]){
        chineseCategories[index++] = this.cateqories[i];

      }
      
    }
    this.fromModel.value.cateqories = chineseCategories;
    this.fromModel.value.rating = this.stock.rating;
    console.log(this.fromModel.value)
    this.router.navigateByUrl('/stock')
  }

}
